//
//  MyTenderJPAllVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2022/3/25.
//  Copyright © 2022 zwb. All rights reserved.
//

import UIKit

 
class ZyaMyTenderJPAllVC: ZyaTenderBaseTableVC,UISearchBarDelegate {
    
    var page = 1
    
    var dataArray = [ZyaZtbContentModel]()
    var z_zb_id = "" // 出价记录使用
    
    var btnflag = "1"
    
    let zhuangtaiArr = ["全部","未成交","已成交","已放弃"]
    let zhuangtaiDic = ["全部":"","未成交":"0","已成交":"1","已放弃":"2"]
    var followTag = ""
    var helper = ZyaTenderHelper()
    private var searchBar:UISearchBar?
    
    
    init(z_zb_id:String = "",searchTitle:String = "",followTag:String = "0") {
        super.init(nibName: nil, bundle: nil)
        self.followTag = followTag
        self.z_zb_id = z_zb_id
        self.helper.filterPa!.searchTitle = searchTitle
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var slideV:SlideView = {
        let v = SlideView(frame: CGRect(x:0,y:0,width: KSGlobal.screenW,height: KSGlobal.screenH), arr: [SlideContent(type: .singleSelect, title: "状态",dataArr: ["全部", "未成交", "已成交"].map{ SeString(title: $0, ks_selected: ($0 == "全部")) },numberOfRow: 3,open: true),SlideContent(type: .singleSelect, title: "时间",dataArr: ["全部", "3日内", "7日内", "1月内", "3月内"].map{ SeString(title: $0, ks_selected: ($0 == "全部")) },numberOfRow: 3,open: true),SlideContent(type: .actionClo,title: "区域", inputStr: "全部",actionClo: { cuIndex in
            
            let vc = ProvinceCityController(selectType: .city)
            vc.citySelectClosure = { province,city in
            
                self.slideV.arr[2].inputStr = city
                self.slideV.tableView.reloadData()
            }
            let window = UIApplication.shared.keyWindow!.rootViewController!
            let nav = BaseNavigationController()
            nav.viewControllers = [vc]
            window.present_FullScreen(to: nav)
        
            
        })])
        return v
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.insertIds2Update()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的报价"
        self.setSearchBar()
        helper.callTableRefreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
            
        }
        
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableView.automaticDimension
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
        tableView.register(XSBaojiaCell.self, forCellReuseIdentifier: XSBaojiaCell.identifier)
     
        
        
        
        
        tableView.tableFooterView = UIView()
        
       
        
        NotificationCenter.default.addObserver(self, selector: #selector(newestBillStatusNotification(_:)), name: Notification.Name(newestBillStatus_notification), object: nil)

      
      }
      @objc func newestBillStatusNotification(_ notification: Notification) {
          // 从通知中获取用户信息
          if let userInfo = notification.userInfo,
             let arr = userInfo["newestBillStatus_data"] as? [NewestModel_Z] {
       
              for i in 0..<self.dataArray.count {
                  let ddd = arr.filter{$0.idKey == self.dataArray[i].zZbId}
                  
                  if ddd.count > 0 {
                      self.dataArray[i].zParallel = ddd.first!.zParallel
                      if ddd.first!.zEndDate.unwrap != "" {
                          self.dataArray[i].zEndDate = ddd.first!.zEndDate
                      }
                      if ddd.first!.zOvertimedNum.unwrap != "" {
                          self.dataArray[i].zOvertimedNum = ddd.first!.zOvertimedNum
                      }
                      self.dataArray[i].zBidCount = ddd.first!.zBidCount
                      self.dataArray[i].zPriceRank = ddd.first!.zPriceRank
   
                  }
              }
              
              self.tableView.reloadData()
              
        
       
          }
      }
     deinit {
    
         NotificationCenter.default.removeObserver(self)
     
     }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    func setSearchBar () {
        searchBar = TenderSearchBar(frame:CGRect(x:5,y:5,width:KSGlobal.screenW - 60,height:40))
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        searchBar?.backgroundImage = UIImage()
       

        searchBar!.searchTextField.backgroundColor = .white
          searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        searchBar!.searchTextField.layer.borderColor = Theme.primaryColor().cgColor
       searchBar!.searchTextField.layer.borderWidth = 1
        
        
        searchBar!.text = self.helper.filterPa!.searchTitle
        searchBar!.placeholder = "搜索报价信息"
        searchBar!.delegate = self
        let searchView = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW ,height:50))
        searchView.addSubview(searchBar!)
        
        self.slideV.confirmClosure = { arr in
            let ss0 = arr[0].dataArr!.filter{ $0.ks_selected }
            if ss0.count > 0 {
                 if ss0.first!.title == "全部" {
                    self.helper.filterPa!.zStatus = ""
 
                    } else if ss0.first!.title == "未成交" {
                        self.helper.filterPa!.zStatus = "0"
 
                    } else if ss0.first!.title == "已成交" {
                        self.helper.filterPa!.zStatus =  "1"
 
                    }
              } else {
                self.helper.filterPa!.zStatus = ""
             }

            
            
            let ss = arr[1].dataArr!.filter{ $0.ks_selected }
            if ss.count > 0 {
                 if ss.first!.title == "全部" {
                    self.helper.filterPa!.startDate = ""
                    self.helper.filterPa!.endDate = ""
                        
                    } else if ss.first!.title == "3日内" {
                        self.helper.filterPa!.startDate = Date.todayPres(3)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "7日内" {
                        self.helper.filterPa!.startDate = Date.todayPres(7)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "1月内" {
                        self.helper.filterPa!.startDate = Date.preMonthsWithNowday(1)
                        self.helper.filterPa!.endDate = Date.today
                        
                    } else if ss.first!.title == "3月内" {
                        self.helper.filterPa!.startDate = Date.preMonthsWithNowday(3)
                        self.helper.filterPa!.endDate = Date.today
                    }
              } else {
                self.helper.filterPa!.startDate = ""
                self.helper.filterPa!.endDate = ""
            }
           let city = arr[2].inputStr

            if city == "全部" {
                self.helper.filterPa!.zCity = ""
            } else {
                self.helper.filterPa!.zCity = city
            }
           
            
            self.slideV.close()
            self.tableView.mj_header?.beginRefreshing()
        }
        
        let moreBtn = UIButton(frame:CGRect(x:KSGlobal.screenW - 50,y:5,width:40 ,height:40))
        moreBtn.setBackgroundImage(UIImage(named: "filter_more"), for: .normal)
        moreBtn.addTouchUpInSideAction { _ in
            
            
            let window = UIApplication.shared.keyWindow!.rootViewController!.view!
            
            window.addSubview(self.slideV)
        }
        searchView.addSubview(moreBtn)
        self.tableView.tableHeaderView = searchView
    
    }
    
   
    @objc func mapAction() {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.helper.filterPa!.searchTitle = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
            let one = self.dataArray[indexPath.row]
  
                guard let cell = tableView.dequeueReusableCell(withIdentifier: XSBaojiaCell.identifier, for: indexPath) as? XSBaojiaCell else {
                    fatalError("cell error")
                }
             
                cell.makeConstrainsts()
        one.listType = .JP
                one.innerType = .jpMyjpKHW
 
        
                cell.one = one
                
                
                return cell
            
            
           
        
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
            var idkey:String = ""
                 idkey = self.dataArray[indexPath.row].zZbId.unwrap
             
            
        zyago2TenderInfoVC(listType: .JP, fromVC:self,idkey:idkey,innerType:.jpListKHW)
            
        
        
        
    }
    func network () {
        let api = API.tender(.queryMytenderJpJoinList(z_begin_dt: self.helper.filterPa!.startDate, z_end_dt: self.helper.filterPa!.endDate, z_city: self.helper.filterPa!.zCity, z_price_min: self.helper.filterPa!.minMoney, z_price_max: self.helper.filterPa!.maxMoney, page: "\(page)", size: "10", z_title: self.helper.filterPa!.searchTitle,z_status: self.helper.filterPa!.zStatus))
        
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZyaZtbContentModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < 10 {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                    
                    self.insertIds2Update()
 
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    func insertIds2Update() {
        let ids = self.dataArray.filter{$0.zZbStatus == "2"}.compactMap{$0.zZbId}
        
        GetNewestUtil_Z.shared.appendIds(ids: ids,type: .JP)
 
    }
}


extension ZyaMyTenderJPAllVC:XYXFilterMenuDataSource {
    // 头部显示要改变的时候回调此方法
    func menu(_ menu: XYXFilterMenu, shouldChange title: String, for indexPath: XYXFilterIndexPath) -> String? {
        
        let titlesStr =  self.helper.titles_jp[indexPath.column!]
        var theTitle = title
        if theTitle == "全部." {
            theTitle = provinceArr[indexPath.row!]
        }
        if theTitle == "全部" {
            theTitle = titlesStr
        }
        return theTitle
    }
    // 每个列展示的数组
    func menu(_ menu: XYXFilterMenu, numberOfRowsAt indexPath: XYXFilterIndexPath) -> Int {
        guard indexPath.column != nil else {
            return 0
        }
        switch indexPath.column! {
        case 0:
            return  zhuangtaiArr.count
        case 1:
            return provinceArr.count
        case 2:
            
                return self.helper.source_jp_status.count
            
            
        case 3:
            return 1
        default:
            return 0
        }
    }
    
    func menu(_ menu: XYXFilterMenu, numberOfItemsAt indexPath: XYXFilterIndexPath) -> Int {
        guard indexPath.column != nil && indexPath.row != nil else {
            return 0
        }
        switch indexPath.column! {
        case 1:
            return cityDic[provinceArr[indexPath.row!]]!.count
        case 3:
            return 1
        default:
            return 0
        }
    }
    // 各个过滤项的 标题数组
    func menu(_ menu: XYXFilterMenu, titleOfRowAt indexPath: XYXFilterIndexPath) -> String {
        let defaultString = ""
        guard indexPath.column != nil && indexPath.row != nil else {
            return defaultString
        }
        switch indexPath.column! {
        case 0: // 状态（采购的时候）
            return  zhuangtaiArr[indexPath.row!]
        case 1: // 区域
            return provinceArr[indexPath.row!]
            
        case 2: // 时间
          
                return self.helper.source_jp_status[indexPath.row!]
          
            
        default:
            return defaultString
        }
    }
    
    func menu(_ menu: XYXFilterMenu, titleOfItemAt indexPath: XYXFilterIndexPath) -> String {
        let defaultString = ""
        guard indexPath.column != nil && indexPath.row != nil && indexPath.item != nil else {
            return defaultString
        }
        if indexPath.column == 1 {
            var cityArr = cityDic[provinceArr[indexPath.row!]]!
            if cityArr.count > 1 {
                cityArr.insert("全部.", at: 0)
            } else {
                
            }
            return cityArr[indexPath.item!]
        }
        return defaultString
    }
    // 大菜单数量
    func numberOfColumns(menu: XYXFilterMenu) -> Int {
        return   self.helper.titles_jp.count
    }
    // 大标题数据
    func menu(_ menu: XYXFilterMenu, titleOfColumnAt index: Int) -> String {
        return   self.helper.titles_jp[index]
    }
    // 菜单的样式，单列表 多列表   collectionview等
    func menu(_ menu: XYXFilterMenu, typeOfColumn: Int) -> XYXFilterView.ColumnType.RawValue {
        switch typeOfColumn {
        case 1:
            return XYXFilterView.ColumnType.TableViewTwo.rawValue
        case 0,2:
            return XYXFilterView.ColumnType.TableViewOne.rawValue
        default:
            return XYXFilterView.ColumnType.collectionViewType.rawValue
        }
    }
    
    func menu(_ menu: XYXFilterMenu, widthOf tableView: UITableView, at column: Int) -> CGFloat {
        if column == 1 {
            if tableView.tag == XYXFilterView.firstTabViewTag{
                return XYX_SCREEN_WIDTH * 0.35
            }else if tableView.tag == XYXFilterView.secondTabViewTag{
                return XYX_SCREEN_WIDTH * 0.65
            }
        }
        return XYX_SCREEN_WIDTH/2
    }
    
    // 菜单向下展开的高度
    func menu(_ menu: XYXFilterMenu, filterContentHeightAt column: Int) -> CGFloat {
        if column == 3 {
            return 200.0
        } else {
            return 300.0
        }
        
    }
    
}
 
